<template>
	<div class="markdown-preview py-5">
		<div v-html="local_content"></div>
	</div>
</template>

<script setup>
import hljs from 'highlight.js'; //需要 npm install highlight.js
import 'highlight.js/styles/atom-one-dark.css'; // 选择一个自己喜欢的样式风格
import MarkdownIt from 'markdown-it'; //需要 npm install markdown-it
import markdownItKatex from 'markdown-it-katex';
import 'katex/dist/katex.min.css'; // 引入 KaTeX 样式

const props = defineProps({
	content: {
		type: String,
		required: true
	}
})

const local_content = ref(props.content)

const md = new MarkdownIt({
	html: true, // 允许在 Markdown 中使用 HTML
	linkify: true, // 自动转换链接为可点击的链接形式
	typographer: true, // 启用智能引号等文本转换功能
	highlight: function (str, lang) {
		if (lang && hljs.getLanguage(lang)) {
			try {
				return `<pre class="hljs"><code>${hljs.highlight(lang, str, true).value}</code></pre>`;
			} catch (error) {
				console.log(error)
			}
		}
		return `<pre class="hljs"><code>${md.utils.escapeHtml(str)}</code></pre>`;
	},
});
md.use(markdownItKatex)


import CryptoJS from 'crypto-js'
// 为标题添加id属性
const addHeadingIds = (html) => {
	return html.replace(/<(h[1-6])>(.*?)<\/\1>/g, (match, tag, content) => {
		// 生成ID，将标题文本转换为小写并替换非字母数字字符为连字符

		const id = CryptoJS.MD5(content).toString();
		// const id = content.toLowerCase().replace(/[^\w]+/g, '-').replace(/-+$/, '');
		return `<${tag} id="${id}">${content}</${tag}>`;
	});
};


watch(
	() => props.content,
	async (new_value) => {
		const markdown_path = useState('path').value
		// console.log('origin', new_value)
		let preview_content = await replaceImageUrl(new_value, markdown_path.substring(0, markdown_path.lastIndexOf('/')))
		// console.log('after', preview_content)
		local_content.value = addHeadingIds(md.render(preview_content))
	}
)

const replaceImageUrl = async (content, file_path) => {
	const backend_url = await getMyBaseURL()

	const replaceFunction = (origin_url) => {
		origin_url = origin_url.replaceAll('\\', '/') // 将 \ 改为 /
		if (origin_url.startsWith('https://') || origin_url.startsWith('http://')) {
			return origin_url
		} else {
			for (let begin in ['D:', 'C:', '~', '/']) {
				if (origin_url.startsWith(begin)) {
					return `${backend_url}/file/markdown/image?path=${origin_url}`;
				}
			}
		}
		return `${backend_url}/file/markdown/image?path=${file_path}/${origin_url}`;
	}

	// 检查 <img> 格式的图片
	const transferImageTag = (content) => {
		let dot_number = 0, l = 0, r = -1;
		for (let i = 0; i < content.length; ++i) {
			while (content[i] == '`') { // 检查 ` 符号，只有在 `` 闭合的时候，markdown的语法才有效。
				dot_number++
				i++
			}
			if (dot_number % 2 == 0) {
				if (content.substring(i, i + 4) == '<img') l = i;
				if (l > 0 && content.substring(i, i + 2) == '/>') r = i + 1;
				if (l > 0 && content.substring(i, i + 6) == '</img>') r = i + 5;
			}
			if (r > l) {
				let reg = ''
				if (content.substring(i, i + 2) == '/>') { // 替换HTML img标签格式 - 自闭合标签
					reg = /(<img\s+[^>]*src\s*=\s*["'])([^"']+)(["'][^>]*\/>)/gi
				}
				if (content.substring(i, i + 6) == '</img>') { // 替换HTML img标签格式 - 结束标签
					reg = /(<img\s+[^>]*src\s*=\s*["'])([^"']+)(["'][^>]*>[\s\S]*?<\/img>)/gi
				}
				let img_tag = content.substring(l, r + 1).replace(reg, (match, prefix, url, suffix) => {
					const newUrl = replaceFunction(url);
					return `${prefix}${newUrl}${suffix}`;
				});
				content = content.substring(0, l) + img_tag + content.substring(r + 1, content.length)
				l = 0
				r = -1
			}
		}
		return content
	}

	// 检查 ![]() 格式的图片
	const transferImageMDFormat = (content) => {
		let dot_number = 0, l = 0, mid = 0, r = 0;
		for (let i = 0; i < content.length; ++i) {
			while (content[i] == '`') {
				dot_number++
				i++
			}
			if (dot_number % 2 == 0) {
				if (content.substring(i, i + 2) == '![') {
					l = i;
					continue
				}

				if (l > 0 && content[i] == ']') {
					mid = i;
					continue
				}

				if (mid > 0) {
					if (content[i] == '(') {
						while (content[i] != ')') {
							r = ++i
						}
					} else if (content[i] != '(') {
						l = 0, mid = 0, r = 0;
					}
				}
			}
			if (r > l) {
				// 替换标准Markdown图片格式
				let img_tag = content.substring(l, r + 1).replace(/!\[(.*?)\]\((.*?)\)/g, (match, alt, url) => {
					const newUrl = replaceFunction(url);
					return `<img alt="${alt}" src="${newUrl}"></img>`;
				});
				content = content.substring(0, l) + img_tag + content.substring(r + 1, content.length)
				l = 0, mid = 0, r = 0;
			}
		}
		return content
	}

	content = transferImageTag(content)
	content = transferImageMDFormat(content)
	return content
}

// 初始化处理
onMounted(() => {
	// 首次渲染
	local_content.value = addHeadingIds(md.render(props.content));
});
</script>
